import 'package:flutter/material.dart';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

//一种允许用户使用给定的相机拍照的屏幕
// A screen that allows users to take a picture using a given camera.
class TakePictureScreen2 extends StatefulWidget {
  const TakePictureScreen2({
    Key? key,
    required this.camera,
  }) : super(key: key);

  final CameraDescription camera;

  @override
  TakePictureScreen2State createState() => TakePictureScreen2State();
}

class TakePictureScreen2State extends State<TakePictureScreen2> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    //从相机显示当前输出， 创建一个CameraController 是真正的相机实例化对象, 我们可以用它来进行录制, 拍照等等
    // To display the current output from the Camera,
    // create a CameraController.
    _controller = CameraController(
      // Get a specific camera from the list of available cameras.从可用相机列表中获取一个特定的相机。
      widget.camera,
      // Define the resolution to use.定义要使用的分辨率。
      // 480p (640x480 on iOS, 720x480 on Android and Web) medium,
      ResolutionPreset.medium,
    );
    //接下来，初始化控制器。这将返回Future。
    // Next, initialize the controller. This returns a Future.
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final deviceRatio = size.width / size.height;
    return Scaffold(
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            //如果Future已完成，则显示预览，拍照窗口出现
            return Container(
              color: Colors.black,
              child: Stack(children: <Widget>[
                Column(children: <Widget>[
                  Expanded(
                    flex: 3,//flex用来设置当前可用空间的占优比
                    child: Stack(children: <Widget>[
                      Center(
                        child: Transform.scale(
                          scale: _controller.value.aspectRatio / deviceRatio,
                          child: AspectRatio(
                            aspectRatio: _controller.value.aspectRatio,
                            child: Center(child: CameraPreview(_controller)),
                          ),
                        ),
                      ),
                      //相机视图
                      /*Container(
                        color: Colors.red,
                        width:double.infinity,
                        // height: double.infinity,
                        child: AspectRatio(
                          aspectRatio: _controller.value.aspectRatio,
                          child: CameraPreview(_controller),
                        ),
                      ),*/
                      //中间：悬浮的身份证框图
                      Positioned(
                        child: Container(
                          // color: Colors.grey,
                          alignment: Alignment.center,
                          margin: const EdgeInsets.fromLTRB(50, 50, 50, 50),
                          child:new Image.asset('assets/images/bg_zm_1.png'),
                        )
                      ),
                      //左上角返回按钮
                      Positioned(
                        top: 15,
                        left: 10,
                        child: IconButton(
                          icon: Icon(
                            Icons.chevron_left,
                            color: Colors.white,
                            size: 30,
                          ),
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        ),
                      ),
                      //左下角：
                      Positioned(
                        bottom: 20.0,
                        left: 30.0,
                        child: IconButton(
                          icon: Icon(
                            Icons.announcement_outlined,
                            color: Colors.white,
                            size: 30,
                          ),
                          onPressed: () {

                          },
                        ),
                      ),
                      //中下拍照：
                      Positioned(
                        bottom: 20.0,
                        left: 160.0,
                        child: IconButton(
                          icon: Icon(
                            Icons.photo_camera,
                            color: Colors.white,
                            size: 30,
                          ),
                          onPressed: () async {
                            try {
                              await _initializeControllerFuture;
                              final image = await _controller.takePicture();
                              await Navigator.of(context).push(
                                MaterialPageRoute(
                                  builder: (context) => DisplayPictureScreen(
                                    imagePath: image.path,
                                  ),
                                ),
                              );
                            } catch (e) {
                              // If an error occurs, log the error to the console. 如果发生错误，将错误记录到控制台。
                              print(e);
                            }
                          },
                        ),
                      ),
                      //右下相册
                      Positioned(
                        bottom: 20.0,
                        right: 30.0,
                        child: IconButton(
                          icon: Icon(
                            Icons.picture_in_picture_alt_outlined,
                            color: Colors.white,
                            size: 30,
                          ),
                          onPressed: () async{
                            var pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);
                            await Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (context) => DisplayPictureScreen(
                                  imagePath: pickedFile!.path,
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ]),
                  ),
                  //拍照操作区域布局
                  /*Expanded(
                    flex: 0,//flex用来设置当前可用空间的占优比
                    child: Align(
                        alignment: Alignment.bottomCenter,
                        child: Container(
                          color: Colors.blueAccent,
                          alignment: Alignment.center,

                          child: IconButton(
                            iconSize: 50.0,
                            icon: Icon(
                              Icons.photo_camera,
                              color: Colors.white,
                            ),
                            onPressed: () async {
                              try {
                                await _initializeControllerFuture;
                                final image = await _controller.takePicture();
                                await Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder: (context) => DisplayPictureScreen(
                                      imagePath: image.path,
                                    ),
                                  ),
                                );
                              } catch (e) {
                                // If an error occurs, log the error to the console. 如果发生错误，将错误记录到控制台。
                                print(e);
                              }
                            },
                          ),

                        )
                      )
                  ),*/
                ],),

                // getPhotoPreview(),//图片预览布局
                // getProgressDialog(),//数据加载中提示框
                // getRestartAlert(),// 身份证识别失败，重新拍照的提示按钮
              ]),
            );
          } else {
            // Otherwise, display a loading indicator. 否则，显示加载中动态样式
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

// A widget that displays the picture taken by the user.显示用户所拍照片的小部件。
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;

  const DisplayPictureScreen({Key? key, required this.imagePath})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Display the Picture')),
      // The image is stored as a file on the device. Use the `Image.file`
      // constructor with the given path to display the image.
      body: Container(
        color: Colors.red,
        child: Image.file(
          File(imagePath),
        ),
      ),
    );
  }
}
